using System.Windows;
using System.Windows.Controls;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace DocumentCreationSystem.Controls;

/// <summary>
/// 思维链查看器控件
/// </summary>
public partial class ThinkingChainViewer : UserControl
{
    private readonly IThinkingChainService _thinkingChainService;
    private readonly ILogger<ThinkingChainViewer> _logger;
    private ThinkingChainResponse? _currentResponse;
    private ThinkingChainDisplayConfig _displayConfig;
    private bool _isExpanded = false;
    private readonly Stopwatch _processStopwatch;

    public ThinkingChainViewer()
    {
        InitializeComponent();
        
        // 在实际应用中，这些服务应该通过依赖注入获取
        _thinkingChainService = new ThinkingChainService(
            Microsoft.Extensions.Logging.Abstractions.NullLogger<ThinkingChainService>.Instance);
        _logger = Microsoft.Extensions.Logging.Abstractions.NullLogger<ThinkingChainViewer>.Instance;
        
        _displayConfig = new ThinkingChainDisplayConfig();
        _processStopwatch = new Stopwatch();
        
        InitializeDisplayConfig();
    }

    public ThinkingChainViewer(IThinkingChainService thinkingChainService, ILogger<ThinkingChainViewer> logger)
    {
        InitializeComponent();
        
        _thinkingChainService = thinkingChainService;
        _logger = logger;
        _displayConfig = thinkingChainService.GetDisplayConfig();
        _processStopwatch = new Stopwatch();
        
        InitializeDisplayConfig();
    }

    private void InitializeDisplayConfig()
    {
        ShowStepNumbersCheckBox.IsChecked = _displayConfig.ShowStepNumbers;
        HighlightKeyStepsCheckBox.IsChecked = _displayConfig.HighlightKeySteps;
        ShowStatisticsCheckBox.IsChecked = false;
        MaxStepsTextBox.Text = _displayConfig.MaxDisplaySteps.ToString();
        
        // 设置显示样式
        foreach (ComboBoxItem item in DisplayStyleComboBox.Items)
        {
            if (item.Tag?.ToString() == _displayConfig.DisplayStyle.ToString())
            {
                DisplayStyleComboBox.SelectedItem = item;
                break;
            }
        }
    }

    /// <summary>
    /// 显示思维链响应
    /// </summary>
    /// <param name="response">思维链响应</param>
    public void DisplayThinkingChain(ThinkingChainResponse response)
    {
        try
        {
            _processStopwatch.Restart();
            
            _currentResponse = response;
            
            // 更新标题信息
            UpdateTitleInfo();
            
            // 清空现有内容
            ThinkingStepsPanel.Children.Clear();
            
            if (response.HasThinkingChain && response.ThinkingSteps.Any())
            {
                // 显示思维链步骤
                DisplayThinkingSteps(response.ThinkingSteps);
                
                // 显示控件
                this.Visibility = Visibility.Visible;
            }
            else
            {
                // 隐藏控件
                this.Visibility = Visibility.Collapsed;
            }
            
            _processStopwatch.Stop();
            UpdateStatistics();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "显示思维链时发生错误");
        }
    }

    /// <summary>
    /// 处理并显示原始内容
    /// </summary>
    /// <param name="rawContent">原始内容</param>
    public void ProcessAndDisplay(string rawContent)
    {
        try
        {
            var response = _thinkingChainService.ParseThinkingChainResponse(rawContent);
            DisplayThinkingChain(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理思维链内容时发生错误");
        }
    }

    private void UpdateTitleInfo()
    {
        if (_currentResponse != null)
        {
            var stepCount = _currentResponse.ThinkingSteps.Count;
            var keyStepCount = _currentResponse.ThinkingSteps.Count(s => s.IsKeyStep);
            
            StepCountText.Text = $"({stepCount} 步骤";
            if (keyStepCount > 0)
            {
                StepCountText.Text += $", {keyStepCount} 关键";
            }
            StepCountText.Text += ")";
        }
    }

    private void DisplayThinkingSteps(List<ThinkingStep> steps)
    {
        var stepsToShow = _displayConfig.MaxDisplaySteps > 0 
            ? steps.Take(_displayConfig.MaxDisplaySteps) 
            : steps;

        foreach (var step in stepsToShow)
        {
            var stepControl = CreateStepControl(step);
            ThinkingStepsPanel.Children.Add(stepControl);
        }
    }

    private UIElement CreateStepControl(ThinkingStep step)
    {
        var border = new Border();
        border.Style = step.IsKeyStep && _displayConfig.HighlightKeySteps 
            ? (Style)FindResource("KeyStepStyle") 
            : (Style)FindResource("ThinkingStepStyle");

        var grid = new Grid();
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
        grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

        // 步骤编号
        if (_displayConfig.ShowStepNumbers)
        {
            var stepNumber = new TextBlock
            {
                Text = $"{step.StepNumber}.",
                Style = (Style)FindResource("StepNumberStyle")
            };
            Grid.SetColumn(stepNumber, 0);
            Grid.SetRow(stepNumber, 0);
            grid.Children.Add(stepNumber);
        }

        // 步骤内容
        var content = new TextBlock
        {
            Text = step.Content,
            Style = (Style)FindResource("StepContentStyle")
        };
        Grid.SetColumn(content, 1);
        Grid.SetRow(content, 0);
        grid.Children.Add(content);

        // 步骤类型
        if (!string.IsNullOrEmpty(step.StepType))
        {
            var stepType = new TextBlock
            {
                Text = step.StepType,
                Style = (Style)FindResource("StepTypeStyle")
            };
            Grid.SetColumn(stepType, 1);
            Grid.SetRow(stepType, 1);
            grid.Children.Add(stepType);
        }

        border.Child = grid;
        return border;
    }

    private void UpdateStatistics()
    {
        if (_currentResponse != null)
        {
            TotalStepsText.Text = _currentResponse.ThinkingSteps.Count.ToString();
            KeyStepsText.Text = _currentResponse.ThinkingSteps.Count(s => s.IsKeyStep).ToString();
            ProcessTimeText.Text = $"{_processStopwatch.ElapsedMilliseconds}ms";
        }
    }

    private void ToggleButton_Click(object sender, RoutedEventArgs e)
    {
        _isExpanded = !_isExpanded;
        
        if (_isExpanded)
        {
            ContentScrollViewer.Visibility = Visibility.Visible;
            ToggleIcon.Kind = PackIconKind.ChevronUp;
        }
        else
        {
            ContentScrollViewer.Visibility = Visibility.Collapsed;
            ToggleIcon.Kind = PackIconKind.ChevronDown;
        }
    }

    private void SettingsButton_Click(object sender, RoutedEventArgs e)
    {
        SettingsPanel.Visibility = SettingsPanel.Visibility == Visibility.Visible 
            ? Visibility.Collapsed 
            : Visibility.Visible;
    }

    private void ExportButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (_currentResponse != null)
            {
                var responses = new List<ThinkingChainResponse> { _currentResponse };
                var exportData = _thinkingChainService.ExportThinkingChainData(responses, "json");
                
                // 这里应该打开保存文件对话框
                // 简化版本：复制到剪贴板
                Clipboard.SetText(exportData);
                
                MessageBox.Show("思维链数据已复制到剪贴板", "导出成功", 
                              MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导出思维链数据时发生错误");
            MessageBox.Show($"导出失败: {ex.Message}", "错误", 
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ApplySettings_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // 更新显示配置
            _displayConfig.ShowStepNumbers = ShowStepNumbersCheckBox.IsChecked ?? true;
            _displayConfig.HighlightKeySteps = HighlightKeyStepsCheckBox.IsChecked ?? true;
            
            if (int.TryParse(MaxStepsTextBox.Text, out var maxSteps))
            {
                _displayConfig.MaxDisplaySteps = maxSteps;
            }
            
            if (DisplayStyleComboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                if (Enum.TryParse<ThinkingChainStyle>(selectedItem.Tag?.ToString(), out var style))
                {
                    _displayConfig.DisplayStyle = style;
                }
            }
            
            // 更新服务配置
            _thinkingChainService.UpdateDisplayConfig(_displayConfig);
            
            // 重新显示当前内容
            if (_currentResponse != null)
            {
                DisplayThinkingChain(_currentResponse);
            }
            
            // 更新统计信息显示
            StatisticsCard.Visibility = ShowStatisticsCheckBox.IsChecked == true 
                ? Visibility.Visible 
                : Visibility.Collapsed;
            
            // 隐藏设置面板
            SettingsPanel.Visibility = Visibility.Collapsed;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "应用设置时发生错误");
            MessageBox.Show($"应用设置失败: {ex.Message}", "错误", 
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ResetSettings_Click(object sender, RoutedEventArgs e)
    {
        _displayConfig = new ThinkingChainDisplayConfig();
        InitializeDisplayConfig();
    }
}
